package com.cai.utils;

import com.cai.ex.ServiceException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Title: JwtUtils
 * @Author RuoLi
 * @Package com.cai.utils
 * @Date 2024/1/12 13:14
 * @description: jwt工具类
 */
@Slf4j
@Component
public class JwtUtils {
    @Value("${jwt.secretKey}")
    private String secretKey;
    @Value("${jwt.expires}")
    private long expires;

    public String createToken(Long id) {
        Date date = new Date(System.currentTimeMillis() + expires * 1000 * 60);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(id.toString())
                .setIssuedAt(new Date())
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    //解析token
    public Claims parseToken(String token) throws ServiceException {
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
    }

    //验证token是否有效
    public boolean validate(String token) {
        return parseToken(token) != null;
    }
}
